import { Injectable } from '@angular/core';
import { App,Platform } from 'ionic-angular';
import { Buffer } from 'buffer';
/*
  Generated class for the UnitsProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class UnitsProvider {

	constructor(
		public app: App,
		public platform: Platform
	) {
		console.log('Hello UnitsProvider Provider');
	}
	//微信内置浏览器
	public isWechat() {
		let ua = window.navigator.userAgent.toLowerCase();
		let item = new RegExp('micromessenger', 'i');
		if (item.test(ua)) {
			return true;
		} else {
			return false;
		}
	}
	//是否app
	public isApp() {
		if (this.platform.is('cordova')) {
			return true;
		} else {
			return false;
		}
	}
	//获取get参数
	public urlParams(name) {
		let lets = new Object();
		let hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		for (let i = 0; i < hashes.length; i++) {
			let done = hashes[i].split('#');
			if (done.length > 1) {
				let hash = done[0].split('=');
				lets[hash[0]] = hash[1];
			} else {
				let hash = hashes[i].split('=');
				lets[hash[0]] = hash[1];
			}
		}
		return lets[name];
	};
	//时间戳转换
	public getIntToDateString(timestamp) {
		let theDate = new Date();
		theDate.setTime(timestamp);
		return theDate.getFullYear() + "-" + (theDate.getMonth() + 1) + "-" + theDate.getDate() + " " +
			theDate.getHours() + ":" + theDate.getMinutes() + ":" + theDate.getSeconds();
	};

	//获取页面跳转(这是非公众号才会使用)
	public isNotWechatToPage() {
		let ionic_data = this.urlParams("ionic");
		if (ionic_data) {
			let json = this.base64Decrypt(ionic_data);
			let data = JSON.parse(json);//转为对象
			let page = data['page'];
			delete data['page'];
			//页面跳转
			this.app.viewDidLoad.emit();
			this.app.viewDidEnter.emit();
			var nav = this.app.getActiveNav();
			nav.push(page, data);
		}
	}

	//加密 
	public base64Encrypt(data: any) {
		return new Buffer(data).toString('base64');
	}

	//解密
	public base64Decrypt(data: any) {
		return new Buffer(data, 'base64').toString();
	}
}